<template>
  <div class="posts-management">
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子标题/内容"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddDialog">新增帖子</el-button>
    </div>
    <el-table :data="filteredPosts" style="margin-top:20px;">
      <el-table-column prop="post_id" label="ID" width="60" />
      <el-table-column prop="user_id" label="用户ID" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="content" label="内容" />
      <el-table-column prop="post_time" label="发布时间" />
      <el-table-column prop="upvotes" label="赞数" />
      <el-table-column prop="downvotes" label="踩数" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="deletePost(row.post_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="标题"><el-input v-model="formData.title" /></el-form-item>
        <el-form-item label="内容"><el-input type="textarea" v-model="formData.content" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePost">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const auth = useAuthStore()
const posts = ref([])
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  post_id: null,
  title: '',
  content: '',
  user_id: auth.userId
})

// 添加过滤后的帖子列表计算属性
const filteredPosts = computed(() => {
  if (!searchQuery.value) return posts.value
  const query = searchQuery.value.toLowerCase()
  return posts.value.filter(post => 
    post.title.toLowerCase().includes(query) ||
    post.content.toLowerCase().includes(query)
  )
})

// 添加搜索处理方法
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

const fetchPosts = async () => {
  try {
    const token = auth.token
    const res = await fetch('http://127.0.0.1:8000/api/forum-posts', {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    posts.value = await res.json()
  } catch (err) {
    ElMessage.error('获取帖子列表失败: ' + err.message)
  }
}

const showAddDialog = () => {
  dialogTitle.value = '新增帖子'
  Object.assign(formData, { post_id: null, title: '', content: '', user_id: auth.userId })
  dialogVisible.value = true
}

const savePost = async () => {
  try {
    if (!formData.title || !formData.content) {
      ElMessage.warning('请填写标题和内容')
      return
    }
    const token = auth.token
    const res = await fetch('http://127.0.0.1:8000/api/forum-posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
      body: JSON.stringify(formData)
    })
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || '操作失败')
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchPosts()
  } catch (err) {
    ElMessage.error(err.message)
  }
}

const deletePost = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该帖子吗？', '提示', { type: 'warning' })
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/forum-posts/${id}?user_id=${auth.userId}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchPosts()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error(err.message || '删除失败')
  }
}

onMounted(fetchPosts)
</script>

<style scoped>
.posts-management {
  padding: 20px;
}
.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.search-input {
  width: 300px;
}
</style> 